import { defineStore } from 'pinia';
import userApi from '../api/user';

// 定义用户类型
interface User {
  id: string;
  username: string;
  email: string;
  // 其他用户属性
}

export const useUserStore = defineStore('user', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user') || 'null') as User | null,
    loading: false,
    error: null as string | null
  }),

  getters: {
    isLoggedIn: (state) => !!state.user,
    currentUser: (state) => state.user
  },

  actions: {
    // 用户注册
    async register(userData: any) {
      this.loading = true;
      this.error = null;
      try {
        const response = await userApi.register(userData);
        // 注册成功后自动登录
        this.user = response.user;
        // 保存用户信息到 localStorage
        localStorage.setItem('user', JSON.stringify(this.user));
        return response;
      } catch (error: any) {
        this.error = error.message || '注册失败';
        console.error('注册失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 用户登录
    async login(credentials: { username: string, password: string }) {
      console.log('userStore.login 开始执行，参数:', credentials);
      this.loading = true;
      this.error = null;
      try {
        console.log('调用 userApi.login...');
        const response = await userApi.login(credentials);
        console.log('userApi.login 返回结果:', response);
        
        this.user = response.user;
        console.log('设置 user:', this.user);
        
        // 保存用户信息到 localStorage
        localStorage.setItem('user', JSON.stringify(this.user));
        
        return response;
      } catch (error: any) {
        this.error = error.message || '登录失败';
        console.error('登录失败详细信息:', error);
        throw error;
      } finally {
        this.loading = false;
        console.log('userStore.login 执行完成，loading 设为 false');
      }
    },

    // 获取用户信息
    async fetchUserInfo() {
      this.loading = true;
      this.error = null;
      try {
        const response = await userApi.getUserInfo();
        this.user = response;
        return response;
      } catch (error: any) {
        this.error = error.message || '获取用户信息失败';
        console.error('获取用户信息失败:', error);
        // 如果获取用户信息失败，可能是未登录，清除登录状态
        if (error.response && error.response.status === 401) {
          this.logout();
        }
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新用户信息
    async updateUserInfo(userData: Partial<User>) {
      this.loading = true;
      this.error = null;
      try {
        const response = await userApi.updateUserInfo(userData);
        this.user = { ...this.user, ...response };
        return response;
      } catch (error: any) {
        this.error = error.message || '更新用户信息失败';
        console.error('更新用户信息失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 检查用户名是否存在
    async checkUsername(username: string) {
      try {
        return await userApi.checkUsername(username);
      } catch (error: any) {
        console.error('检查用户名失败:', error);
        throw error;
      }
    },

    // 检查邮箱是否存在
    async checkEmail(email: string) {
      try {
        return await userApi.checkEmail(email);
      } catch (error: any) {
        console.error('检查邮箱失败:', error);
        throw error;
      }
    },

    // 用户登出
    logout() {
      this.user = null;
      // 清除 localStorage 中的用户信息
      localStorage.removeItem('user');
    }
  }
});
